import { sport_map } from '../../utils/dataset/db_data'

Page({
  data: {
    skuList: [],  // court_id, rid
    lockSubmit: 0,
  },
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('init', (data) => {
      this.setData(data);
      this.setData({ sportName: sport_map.get(data.sportId) });
    })
  },
  async onSubmit() {
    this.setData({ lockSubmit: 1 });
    // 1. 锁场，校验场地状态
    let flag = await this.lockAppointment();
    if (!flag) return;
    // 2. 生成订单，写入订单变动
    await this.generateOrder();
    this.setData({ lockSubmit: 0 });
  },
  async lockAppointment() {
    const res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_appointment',
        data: {
          funcName: 'lockAppointment',
          appointmentId: this.data.appointmentId,
          skuList: this.data.skuList
        },
        success: (r) => resolve(r.result),
      })
    })
    if (!res.errMsg) {
      return 1;
    } else {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
      return 0;
    }
  },
  async generateOrder() {
    const res = await new Promise(resolve => {
      wx.cloud.callFunction({
        name: 'db_order',
        data: {
          funcName: 'insert',
          appointment_id: this.data.appointmentId,
          sku_list: this.data.skuList
        },
        success: (r) => resolve(r.result)
      })
    })
    if (!res.errMsg) {
      wx.redirectTo({
        url: `/pages/creator/payment?price=${res.payment_price}&stadiumName=${this.data.stadiumName}&dateStr=${this.data.dateInfo.dateStr}&orderId=${res.order_id}`,
      })
    } else {
      wx.showToast({
        title: res.errMsg,
        icon: 'none'
      })
    }
  },
  navigateTo() {
    wx.navigateTo({
      url: '/pages/templates/notice?type=reservation',
    })
  },
})